//
//  VideoPhotoViewController.m
//  Rail
//
//  Created by hychen on 2018/3/8.
//  Copyright © 2018年 Hychen. All rights reserved.
//

#import "VideoPhotoViewController.h"
#import "HttpRequest.h"
#import "LineDetailDescTableViewCell.h"
#import "CapturePhotoTableViewCell.h"
#import "ButtonTableViewCell.h"
#import "TextViewTableViewCell.h"
#import "NSDate+Category_lib.h"
#import "BMUsefulPickerView.h"
#import "SelectTimeTableViewCell.h"
#import "WatchVideoViewController.h"

@interface VideoPhotoViewController ()<UITableViewDelegate,UITableViewDataSource,YCTextViewDelegate>

@property (nonatomic, strong) NSArray *dataArray;

@property (nonatomic, strong) UIButton *linePhoto;
@property (nonatomic, strong) UIButton *warnPhoto;
@property (nonatomic, strong) UIButton *warnVideo;

@property (nonatomic, assign) NSInteger maxCountImage;

@property (nonatomic, assign) WarnLevelType warnLevelType;

@property (nonatomic, weak) YCTextView *textView;

@property (nonatomic, copy) NSString *noteContent;
@property (nonatomic, copy) NSString *warnContent;

@property (nonatomic, assign) BOOL isUploading;

@property (nonatomic, strong) NSDate *fromDate;
@property (nonatomic, strong) NSDate *toDate;

@end

@implementation VideoPhotoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _maxCountImage = 3;
    _warnLevelType = -1;
    
    UIView *bgView = [UIView new];
    bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgView];
    
    self.linePhoto = [UIButton buttonWithTitle:@"抓取巡线照片" titleColor:ColorDefalutGray norImage:ImageNamed_bb(@"monitoring_take_btn_n") highImage:ImageNamed_bb(@"monitoring_take_btn_p") action:@selector(clickLinePhoto) owner:self];
    [self.linePhoto setTitleColor:kWhiteColor forState:UIControlStateHighlighted];
    [self.view addSubview:self.linePhoto];
    [self.linePhoto mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(45);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(45);
        make.top.mas_equalTo(ResizeH(50));
    }];
    
    self.warnPhoto = [UIButton buttonWithTitle:@"抓取报警照片" titleColor:ColorDefalutGray norImage:ImageNamed_bb(@"monitoring_take_btn_n") highImage:ImageNamed_bb(@"monitoring_take_btn_p") action:@selector(clickWarnPhoto) owner:self];
    [self.warnPhoto setTitleColor:kWhiteColor forState:UIControlStateHighlighted];
    [self.view addSubview:self.warnPhoto];
    [self.warnPhoto mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(45);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(45);
        make.top.equalTo(self.linePhoto.mas_bottom).offset(ResizeH(25));
    }];
    
    self.warnVideo = [UIButton buttonWithTitle:@"抓取报警视频" titleColor:ColorDefalutGray norImage:ImageNamed_bb(@"monitoring_take_btn_n") highImage:ImageNamed_bb(@"monitoring_take_btn_p") action:@selector(clickWarnVideo) owner:self];
    [self.warnVideo setTitleColor:kWhiteColor forState:UIControlStateHighlighted];
    [self.view addSubview:self.warnVideo];
    [self.warnVideo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(45);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(45);
        make.top.equalTo(self.warnPhoto.mas_bottom).offset(ResizeH(25));
    }];
    
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        make.bottom.equalTo(self.warnVideo.mas_bottom).offset(ResizeH(50));
    }];
    
    
    [self.view addSubview:self.tableView];
    self.tableView.hidden = YES;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)clickLinePhoto {
    if (self.showType == showTypeLinePhoto) {
        return;
    }
    [self.tableView setContentOffset:CGPointZero];
    [self.selectImageArray removeAllObjects];
    [self setupLinePhotoDataArray];
    self.tableView.hidden = NO;

}

- (void)clickWarnPhoto {
    if (self.showType == showTypeWarnPhoto) {
        return;
    }
    self.warnLevelType = -1;
    [self.tableView setContentOffset:CGPointZero];
    [self.selectImageArray removeAllObjects];
    [self setupLineWarnPhotoDataArray];
    self.tableView.hidden = NO;
}

- (void)clickWarnVideo {
    if (self.showType == showTypeWarnVideo) {
        return;
    }
    self.toDate = [[NSDate date] dateBySubtractingMinutes:20];
    self.fromDate = [self.toDate dateBySubtractingMinutes:5];
    self.warnLevelType = -1;
    [self.tableView setContentOffset:CGPointZero];
    [self.selectImageArray removeAllObjects];
    [self setupWarnVideoDataArray];
    self.tableView.hidden = NO;
}

- (void)addCapturePhoto:(UIImage *)image {
    if (image) {
        CapturePhotoModel *model = [[CapturePhotoModel alloc] initWithImage:image];
        [self.selectImageArray addObject:model];
        [self reloadData];
    }
}

#pragma mark - YCTextViewDelegate
- (void)YCTextView:(YCTextView *)YCTextView textDidChanged:(NSString *)text {
    if (self.showType == showTypeLinePhoto) {
        self.noteContent = text;
    }
    else if (self.showType == showTypeWarnPhoto || self.showType == showTypeWarnVideo
             ) {
        self.warnContent = text;
    }
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary *dict = [self.dataArray objectAtIndexSafe:indexPath.row];
    
    NSString *type = dict[@"type"];
    NSString *title = dict[@"title"];
    
    if ([type isEqualToString:@"text"]) {
        LineDetailDescTableViewCell *cell = [LineDetailDescTableViewCell cellWithTableView:tableView class:[LineDetailDescTableViewCell class]];
        cell.titleLabel.text = title?:@"";
        
        NSString *content = [dict objectForKey:@"content"];
        if (content.length > 0) {
            cell.contentLabel.text = content;
            cell.isPlaceholder = YES;
        }
        else {
            cell.contentLabel.text = [dict objectForKey:@"placeholder"];
            cell.isPlaceholder = NO;
        }
        
        NSString *placeholder = [dict objectForKey:@"placeholder"];
        if ([placeholder isKindOfClass:[NSString class]] && placeholder.length > 0) {
            cell.showArrow = YES;
        }
        else {
            cell.showArrow = NO;
        }

        return cell;
    }
    else if ([type isEqualToString:@"image"]) {
        CapturePhotoTableViewCell *cell = [CapturePhotoTableViewCell cellWithInitStyleTableView:tableView class:[CapturePhotoTableViewCell class]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setTitle:title?:@"抓拍照片"];
        [cell setPhotoArray:self.selectImageArray];
        BMWeakSelf
        [cell setBlockClickPhoto:^(CapturePhotoModel *model) {
            if (model.isAddPhoto) {
                [weakSelf capturePhoto];
            }
        }];
        
        [cell setBlockSelectPhotoArray:^(NSArray *photoArray) {
            weakSelf.selectImageArray = [NSMutableArray arrayWithArray:photoArray];
            [weakSelf reloadData];
//            if (weakSelf.showType == showTypeLinePhoto) {
//                [weakSelf setupLinePhotoDataArray];
//            }
//            else if (weakSelf.showType == showTypeWarnPhoto) {
//                [weakSelf setupLineWarnPhotoDataArray];
//            }
        }];
        return cell;
    }
    else if ([type isEqualToString:@"button"]) {
        ButtonTableViewCell *cell = [ButtonTableViewCell cellWithTableView:tableView class:[ButtonTableViewCell class]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.buttonTitle = title?:@"保存";
        BMWeakSelf
        [cell setBlockClickEventButton:^{
            [weakSelf handleSubmit];
        }];
        
        return cell;
    }
    else if ([type isEqualToString:@"textview"]) {
        TextViewTableViewCell *cell = [TextViewTableViewCell cellWithInitStyleTableView:tableView class:[TextViewTableViewCell class]];
        cell.textView.delegate = self;
        cell.titleLabel.text = title;
        cell.textView.text = [dict objectForKey:@"content"]?:@"";
        self.textView = cell.textView;
        return cell;
    }
    else if ([type isEqualToString:@"time"]) {
        SelectTimeTableViewCell *cell = [SelectTimeTableViewCell cellWithInitStyleTableView:tableView class:[SelectTimeTableViewCell class]];
        cell.toDate = self.toDate;
        cell.fromDate = self.fromDate;
        BMWeakSelf
        [cell setBlockSelectToDate:^(NSDate *toDate) {
            weakSelf.toDate = toDate;
        }];
        [cell setBlockSelectFromDate:^(NSDate *fromDate) {
            weakSelf.fromDate = fromDate;
        }];
        return cell;
    }
    
    return [UITableViewCell new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dict = [self.dataArray objectAtIndexSafe:indexPath.row];
    
    NSString *type = dict[@"type"];
    
    if ([type isEqualToString:@"text"]) {

        return 45.f;
    }
    else if ([type isEqualToString:@"image"]) {

        return 160.f;
    }
    else if ([type isEqualToString:@"button"]) {

        return 120.f;
    }
    else if ([type isEqualToString:@"textview"]) {

        return 190.f;
    }
    else if ([type isEqualToString:@"time"]) {
        return 120.f;
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    BMWeakSelf
    if (self.showType == showTypeWarnPhoto && indexPath.row == 2) {
        [BMUsefulPickerView showSingleColPickerWithToolBarText:@"请选择事件级别" data:@[@"普通",@"警告",@"严重",@"重大"] defaultIndex:self.warnLevelType toolBarStyle:BMPickerViewToolBarStyleText cancelBlock:^{
            
        } clickBlock:^(NSInteger selectedIndex, NSString *selectedValue) {
            weakSelf.warnLevelType = selectedIndex;
            [weakSelf setupLineWarnPhotoDataArray];
        }];
    }
    else if (self.showType == showTypeWarnVideo && indexPath.row == 2) {
        [BMUsefulPickerView showSingleColPickerWithToolBarText:@"请选择事件级别" data:@[@"普通",@"警告",@"严重",@"重大"] defaultIndex:self.warnLevelType toolBarStyle:BMPickerViewToolBarStyleText cancelBlock:^{
            
        } clickBlock:^(NSInteger selectedIndex, NSString *selectedValue) {
            weakSelf.warnLevelType = selectedIndex;
            [weakSelf setupWarnVideoDataArray];
        }];
    }
}

- (void)reloadData {
    if (self.showType == showTypeLinePhoto) {
        [self setupLinePhotoDataArray];
    }
    else if (self.showType == showTypeWarnPhoto) {
        [self setupLineWarnPhotoDataArray];
    }
}

- (void)setupLinePhotoDataArray {
    self.showType = showTypeLinePhoto;
    self.dataArray = @[
                       @{@"type":@"image",@"title":[NSString stringWithFormat:@"抓拍照片 %ld/%ld",self.selectImageArray.count,_maxCountImage]},
                       @{@"type":@"textview",@"title":@"备注内容",@"content":self.noteContent?:@""},
                       @{@"type":@"button",@"title":@"保存"},
                       ];
    
    [self.tableView reloadData];
}

- (void)setupLineWarnPhotoDataArray {
    self.showType = showTypeWarnPhoto;
    
    WarnLevelInfoModel *model = [WarnLevelConfig warnLevelInfoWithType:self.warnLevelType];
    
    self.dataArray = @[
                       @{@"type":@"image",@"title":[NSString stringWithFormat:@"抓拍照片 %ld/%ld",self.selectImageArray.count,_maxCountImage]},
                       @{@"type":@"text",@"title":@"事件名称",@"content":@"人工抓拍报警事件"},
                       @{@"type":@"text",@"title":@"事件级别",@"content":model.title?:@"",@"placeholder":@"请选择"},
                       @{@"type":@"textview",@"title":@"报警内容",@"content":self.warnContent?:@""},
                       @{@"type":@"button",@"title":@"保存"},
                       ];
    
    [self.tableView reloadData];
}

- (void)setupWarnVideoDataArray {
    self.showType = showTypeWarnVideo;
    
    WarnLevelInfoModel *model = [WarnLevelConfig warnLevelInfoWithType:self.warnLevelType];
    
    self.dataArray = @[
                       @{@"type":@"time"},
                       @{@"type":@"text",@"title":@"事件名称",@"content":@"人工抓拍报警事件"},
                       @{@"type":@"text",@"title":@"事件级别",@"content":model.title?:@"",@"placeholder":@"请选择"},
                       @{@"type":@"textview",@"title":@"报警内容",@"content":self.warnContent?:@""},
                       @{@"type":@"button",@"title":@"保存"},
                       ];
    
    [self.tableView reloadData];
}

- (void)handleSubmit {
    if (self.showType == showTypeLinePhoto) {
        [self requestLinePhotoData];
    }
    else if (self.showType == showTypeWarnPhoto) {
        [self requestWarnPhotoData];
    }
    else if (self.showType == showTypeWarnVideo) {
        [self requestWarnVideoData];
    }
}

- (void)capturePhoto {
    //抓取图片
    if (self.BlockCapturePhoto) {
        self.BlockCapturePhoto();
    }
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (NSMutableArray *)selectImageArray {
    if (!_selectImageArray) {
        _selectImageArray = [NSMutableArray array];
    }
    return _selectImageArray;
}

#pragma mark - 网络请求
- (void)requestLinePhotoData {
    
    if (self.isUploading) {
        return;
    }
    
    if (self.selectImageArray.count < 1) {
        Show_Msg_Error(@"请至少抓拍一张照片")
        return;
    }
    
    BMWeakSelf
    if (![BMUtils checkOpen4gAutoUploadWithCompletion:^{
        [weakSelf _requestLinePhotoData];
    }]) {
        return;
    }
    
    [self _requestLinePhotoData];
}

- (void)_requestLinePhotoData {
    BMWeakSelf
    
    UIImage *image1 = nil;
    UIImage *image2 = nil;
    UIImage *image3 = nil;
    for (int i = 0; i < self.selectImageArray.count; ++i) {
        UIImage *image = ((CapturePhotoModel *)[self.selectImageArray objectAtIndex:i]).uploadImage;
        if (i == 0) {
            image1 = image;
        }
        if (i == 1) {
            image2 = image;
        }
        if (i == 2) {
            image3 = image;
        }
    }
    
    self.isUploading = YES;
    
    Show_Msg(@"上传中")
    [HttpRequest uploadPatrolLineDataWithAreaId:self.selectDeviceModel.areaid?:@"" deviceId:self.selectDeviceModel.deviceid?:@"" deviceName:self.selectDeviceModel.device_name?:@"" channelName:self.selectDeviceModel.ch_name?:@"" note:self.noteContent?:@"" image1:image1 image2:image2 image3:image3 success:^(id object) {
        weakSelf.isUploading = NO;
        Show_Msg_Success(@"上传成功")
        if (weakSelf.BlockUploadLinePhotoSuccess) {
            weakSelf.BlockUploadLinePhotoSuccess();
        }
    } failure:^(NSString *code, NSString *msg) {
        weakSelf.isUploading = NO;
        Show_Msg_Error(msg?:@"上传失败")
    }];
    
}

- (void)requestWarnPhotoData {
    self.warnContent = self.textView.text;
    
    if (self.selectImageArray.count == 0) {
        Show_Msg_Error(@"请抓取一张照片")
        return;
    }
    
//    if (self.warnLevelType == -1) {
//        Show_Msg_Error(@"请选择事件级别")
//        return;
//    }
    
    if (self.warnContent.length == 0) {
        Show_Msg_Error(@"请填写报警内容")
        return;
    }
    
    if (self.isUploading) {
        return;
    }
    
    if (!self.selectDeviceModel) {
        return;
    }
    
    BMWeakSelf
    if (![BMUtils checkOpen4gAutoUploadWithCompletion:^{
        [weakSelf _requestWarnPhotoData];
    }]) {
        return;
    }
    
    [self _requestWarnPhotoData];
}

- (void)_requestWarnPhotoData {
    BMWeakSelf
    
    UIImage *image1 = nil;
    UIImage *image2 = nil;
    UIImage *image3 = nil;
    for (int i = 0; i < self.selectImageArray.count; ++i) {
        UIImage *image = ((CapturePhotoModel *)[self.selectImageArray objectAtIndex:i]).uploadImage;
        if (i == 0) {
            image1 = image;
        }
        if (i == 1) {
            image2 = image;
        }
        if (i == 2) {
            image3 = image;
        }
    }

    NSString *eventLevel = [@(self.warnLevelType) stringValue];
    
    NSString *time = [[NSDate date] formatYearMonthDayHourSecond_lib];
    
    self.isUploading = YES;
    
    Show_Msg(@"上传中")
    [HttpRequest addAlertRecordWithAreaId:self.selectDeviceModel.areaid?:@"" deviceId:self.selectDeviceModel.deviceid?:@"" deviceName:self.selectDeviceModel.device_name?:@"" chNo:self.selectDeviceModel.chid?:@"" content:self.warnContent?:@"" alertType:@"00" eventId:@"b0119999" eventType:@"100" eventLevel:eventLevel startTime:time endTime:time sourceType:@"1" snapshotImage1:image1 snapshotImage2:image2 snapshotImage3:image3 videoUrl:nil success:^(id object) {
        Show_Msg_Success(@"上传成功")
        weakSelf.isUploading = NO;
        if (weakSelf.BlockUploadWarnPhotoSuccess) {
            weakSelf.BlockUploadWarnPhotoSuccess();
        }
    } failure:^(NSString *code, NSString *msg) {
        weakSelf.isUploading = NO;
        Show_Msg_Error(msg?:@"上传失败")
    }];
}

- (void)requestWarnVideoData {
    
    if (self.fromDate == nil) {
        Show_Msg_Error(@"请选择起始时间")
        return;
    }
    
    if (self.toDate == nil) {
        Show_Msg_Error(@"请选择结束时间")
        return;
    }
    
//    if (self.warnLevelType == -1) {
//        Show_Msg_Error(@"请选择事件级别")
//        return;
//    }
    
    if (self.warnContent.length == 0) {
        Show_Msg_Error(@"请填写报警内容")
        return;
    }
    
    if (self.isUploading) {
        return;
    }
    
    if (!self.selectDeviceModel) {
        return;
    }
    
    BMWeakSelf
    if (![BMUtils checkOpen4gAutoUploadWithCompletion:^{
        [weakSelf requestWarnVideoData];
    }]) {
        return;
    }
    
    if (self.BlockUploadWarnVideoSuccess) {
        self.BlockUploadWarnVideoSuccess(self.fromDate, self.toDate);
    }
}

- (void)_requestWarnVideoData:(NSData *)videoData {
    BMWeakSelf
    
    NSString *eventLevel = [@(self.warnLevelType) stringValue]?:@"";
    
    NSString *startTime = [self.fromDate formatYearMonthDayHourSecond_lib]?:@"";
    
    NSString *endTime = [self.toDate formatYearMonthDayHourSecond_lib]?:@"";
    
    self.isUploading = YES;
    
    Show_Msg(@"上传中")
    [HttpRequest addAlertRecordWithAreaId:self.selectDeviceModel.areaid?:@"" deviceId:self.selectDeviceModel.deviceid?:@"" deviceName:self.selectDeviceModel.device_name?:@"" chNo:self.selectDeviceModel.chid?:@"" content:self.warnContent?:@"" alertType:@"00" eventId:@"b0119999" eventType:@"100" eventLevel:eventLevel startTime:startTime endTime:endTime sourceType:@"1" snapshotImage1:nil snapshotImage2:nil snapshotImage3:nil videoUrl:videoData success:^(id object) {
        Show_Msg_Success(@"上传成功")
        weakSelf.isUploading = NO;
    } failure:^(NSString *code, NSString *msg) {
        weakSelf.isUploading = NO;
        Show_Msg_Error(msg?:@"上传失败")
    }];
}
@end
